package com.example.qqlaobing.Umoney.view.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


import com.authreal.api.AuthBuilder;
import com.authreal.api.OnResultListener;
import com.example.qqlaobing.Umoney.R;
import com.example.qqlaobing.Umoney.adapter.CertificationAdapter;
import com.example.qqlaobing.Umoney.application.GeneralApplication;
import com.example.qqlaobing.Umoney.been.PostBean;
import com.example.qqlaobing.Umoney.been.postselectProductsBean;
import com.example.qqlaobing.Umoney.been.verifyBean;
import com.example.qqlaobing.Umoney.net.NetRequestBusinessDefine;
import com.example.qqlaobing.Umoney.net.NetRequestRULBuilder;
import com.example.qqlaobing.Umoney.presenter.presenterImpl.CenterPresenterImpl;
import com.example.qqlaobing.Umoney.presenter.presenterImpl.HomePresenterImpl;
import com.example.qqlaobing.Umoney.utils.GenerateSign;
import com.example.qqlaobing.Umoney.utils.HttpRequestCallBack;
import com.example.qqlaobing.Umoney.utils.HttpRequestManager;
import com.example.qqlaobing.Umoney.utils.ImgErToFileUtil;
import com.example.qqlaobing.Umoney.utils.permission.RxPermissions;
import com.example.qqlaobing.Umoney.utils.permission.SchedulerTransformer;
import com.example.qqlaobing.Umoney.view.fragment.ReListView;
import com.example.qqlaobing.Umoney.view.fragment.my.Dilog_TiShi;
import com.example.qqlaobing.Umoney.view.idcard.IDCardBothActivity;
import com.example.qqlaobing.Umoney.view.idcard.LFSettingUtils;
import com.example.qqlaobing.Umoney.view.idcard.LFSpUtils;
import com.example.qqlaobing.Umoney.view.lfiliveness.Constants1;
import com.example.qqlaobing.Umoney.view.lfiliveness.LFCommonUtils;
import com.example.qqlaobing.Umoney.view.lfiliveness.LFSpUtils1;
import com.example.qqlaobing.Umoney.view.myview.LoadingDialog;
import com.githang.statusbar.StatusBarCompat;
import com.google.gson.Gson;
import com.gyf.barlibrary.ImmersionBar;
import com.linkface.card.CardActivity;
import com.linkface.liveness.LFLivenessSDK;
import com.linkface.liveness.network.LFLiDownloadManager;
import com.linkface.liveness.ui.LivenessActivity;
import com.linkface.liveness.util.Constants;
import com.linkface.liveness.util.LFLog;
import com.linkface.liveness.util.LFProtoBufUtil;
import com.linkface.liveness.util.LFReturnResult;
import com.linkface.liveness.util.LivenessUtils;
import com.linkface.utils.LFIntentTransportData;
import com.megvii.faceidiol.sdk.manager.IDCardDetectListener;
import com.megvii.faceidiol.sdk.manager.IDCardManager;
import com.megvii.faceidiol.sdk.manager.IDCardResult;
import com.megvii.faceidiol.sdk.manager.UserDetectConfig;
import com.megvii.meglive_sdk.listener.DetectCallback;
import com.megvii.meglive_sdk.listener.PreCallback;
import com.megvii.meglive_sdk.manager.MegLiveManager;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;

import cn.linkface.idcard.LFIDCard;
import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import sun.misc.BASE64Decoder;
/**
 * 认证中心
 *
 * @author zlz
 */
public class CertificationCenterActivity extends AppCompatActivity implements View.OnClickListener {
    private TextView btnGetAmount;
    private String authKey = "f932ff6d-6c73-4c31-9acf-b97575fc31ca";
    private String urlNotify = "http://211.149.180.198";
    private ReListView lvCertification;
    private int[] inco = {R.mipmap.cyfq_icon_authentication_ed, R.mipmap.cyfq_icon_information_ed, R.mipmap.cyfq_icon_operator_ed, R.mipmap.cyfq_icon_work_certification_ed,
            R.mipmap.cyfq_icon_zhima_ed, R.mipmap.cyfq_icon_bank_card_ed};
    private int[] inco1 = {R.mipmap.cyfq_icon_authentication, R.mipmap.cyfq_icon_information, R.mipmap.cyfq_icon_operator, R.mipmap.cyfq_icon_work_certification,
            R.mipmap.cyfq_icon_zhima, R.mipmap.cyfq_icon_bank_card};
    private List<String> data1;
    private String[] list = new String[inco.length];
    private ImageView tv_exit;
    String apiKey = "rh1wPIb9gBIxgZjlkgYKCogjhIIFneMc";
    String secret = "FTX_JrMkBx2nYK-avr6itodpizQU3Y-z";
    long currtTime = System.currentTimeMillis() / 1000;
    long expireTime = System.currentTimeMillis() / 1000 + 60 * 60 * 24;
    private CertificationAdapter certificationAdapter;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (null == msg) {
                return;
            }
            switch (msg.what) {
                case NetRequestBusinessDefine.K_HOME:
                    try {
                        if (msg.arg1 == 404) {
                            return;
                        }
                        Log.e("111", "main1");
                        JSONObject response = (JSONObject) msg.obj;
                        String resultCode = response.getString("status");
                        if (resultCode.equals("1")) {
                            JSONObject results = response.getJSONObject("data");
                            JSONObject data = results.getJSONObject("data");
                            Log.e("111", data.getString("authstatus"));
                            if (data.getString("authstatus").equals("1")) {
                                Intent intent = new Intent(CertificationCenterActivity.this, MainActivity.class);
                                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                                NetRequestBusinessDefine.login = true;
                                startActivity(intent);
                                finish();
                            } else {
                                Log.e("111", "main");
                                Toast.makeText(CertificationCenterActivity.this, "资料填写不完善", Toast.LENGTH_LONG).show();
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case NetRequestBusinessDefine.K_GET_AUTHINFO:
                    try {
                        if (msg.arg1 == 404) {
                            return;
                        }
                        JSONObject response = (JSONObject) msg.obj;
                        String resultCode = response.getString("status");
                        if (resultCode.equals("1")) {
                            JSONObject results = response.getJSONObject("data");
                            JSONObject data = results.getJSONObject("data");
                            if (data.getString("cominfo").equals("1")) {
                                list[0] = "已完善";
                            } else {
                                list[0] = "未认证";
                            }
                            if (data.getString("gz").equals("1")) {
                                list[1] = "已完善";
                            } else {
                                list[1] = "未认证";
                            }
                            if (data.getString("contacts").equals("1")) {
                                list[2] = "已完善";
                            } else {
                                list[2] = "未认证";
                            }
//                            if (data.getString("tmobile").equals("1")) {
//                                list[3] = "已完善";
//                            } else {
//                                list[3] = "未认证";
//                            }
                            if (data.getString("zmf").equals("1")) {
                                list[3] = "已完善";
                            } else {
                                list[3] = "未认证";
                            }
                            if (data.getString("bank").equals("1")) {
                                list[4] = "已完善";
                            } else {
                                list[4] = "未认证";
                            }
                            certificationAdapter = new CertificationAdapter(CertificationCenterActivity.this, data1, inco, inco1, list);
                            lvCertification.setAdapter(certificationAdapter);
                            lvCertification.loadComplete();
                            for (int i = 0; i < list.length; i++) {
                                if (list[i].equals("未认证")) {//判断为未认证！
                                    btnGetAmount.setSelected(true);
                                    return;
                                }
                            }
                            btnGetAmount.setSelected(false);
                        } else {
                            lvCertification.loadComplete();
                            Toast.makeText(CertificationCenterActivity.this, response.getString("msg"), Toast.LENGTH_LONG).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;
                default:
                    break;
            }
        }
    };
    private String url;
    private LoadingDialog loadingDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_certification);
        ImmersionBar.with(this).init();
        ImmersionBar.with(this).statusBarDarkFont(true).init();
        initview();
        initData();
    }

    Dilog_TiShi tiShi;
    private MegLiveManager megLiveManager;

    private void initData() {
        initSDK();
        megLiveManager = MegLiveManager.getInstance();
        /**
         * 如果build.gradle中的applicationId 与 manifest中package不一致，必须将manifest中package通过
         * 下面方法传入，如果一致可以不调用此方法
         */
        megLiveManager.setManifestPack(this, "com.megvii.meglive_still.demo");
        btnGetAmount.setOnClickListener(this);
        tv_exit.setOnClickListener(this);
        tiShi = new Dilog_TiShi(this, new Dilog_TiShi.OnBackCenter() {
            @Override
            public void onBackCenter() {//立即拿钱
//                Intent intent = new Intent(CertificationCenterActivity.this, MainActivity.class);
//                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
//                NetRequestBusinessDefine.login = true;
//                startActivity(intent);
//                finish();
                tiShi.dismiss();
            }

            @Override
            public void onBackCancle() {//残忍决绝
                finish();
            }
        });
        data1 = new ArrayList<>();
        data1.add("个人信息");
        data1.add("工作认证");
        data1.add("紧急联系人");
//        data1.add("运营商信息");
        data1.add("芝麻信用");
        data1.add("收款银行卡");
        lvCertification.setInterface(new ReListView.LoadListener() {
            @Override
            public void onLoad() {
                lvCertification.loadComplete();
            }

            @Override
            public void pullLoad() {
                Log.e("re", "1111");
                CenterPresenterImpl centerPresenter = new CenterPresenterImpl(mHandler);
                centerPresenter.postData();
            }
        });
        lvCertification.setOnItemClickListener((adapterView, view, i, l) -> {
            switch (i - 1) {
                case 0:
                    if (list[0].equals("未认证")) {
                        new RxPermissions(this)
                                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                        Manifest.permission.READ_EXTERNAL_STORAGE,
                                        Manifest.permission.CAMERA)
                                .compose(new SchedulerTransformer<Boolean>())
                                .subscribe(aBoolean -> {
                                    if (aBoolean) {
                                        toScanIdCardBoth();
                                    } else {
                                        finish();
                                        Toast.makeText(this, "请允许打开权限！", Toast.LENGTH_LONG).show();
                                    }
                                });
                    } else if (list[0].equals("已完善")) {
                        Intent intent = new Intent(CertificationCenterActivity.this, UserInfoActivity.class);
                        intent.putExtra("title", "show");
                        startActivity(intent);
                    } else {
                        Toast.makeText(CertificationCenterActivity.this, "请按顺序认证", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case 1:
                    if (list[1].equals("未认证")) {
                        startActivityForResult(new Intent(CertificationCenterActivity.this, WorkCheckActivity.class), 2);
                    } else {
                        Toast.makeText(CertificationCenterActivity.this, "请按顺序认证", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case 2:
                    if (list[2].equals("未认证")) {
                        startActivityForResult(new Intent(CertificationCenterActivity.this, ContactActivity.class), 3);

                    } else {
                        Toast.makeText(CertificationCenterActivity.this, "请按顺序认证", Toast.LENGTH_SHORT).show();
                    }
                    break;
//                case 3:
//                    if (list[3].equals("未认证")) {
//                        startActivityForResult(new Intent(CertificationCenterActivity.this, WebOpeActivity.class), 4);
//
//                    } else {
//                        Toast.makeText(CertificationCenterActivity.this, "请按顺序认证", Toast.LENGTH_SHORT).show();
//                    }
//                    break;
                case 3:
                    if (list[3].equals("未认证")) {
                        startActivityForResult(new Intent(CertificationCenterActivity.this, ZhiMaActivity.class), 5);

                    } else {
                        Toast.makeText(CertificationCenterActivity.this, "请按顺序认证", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case 4:
                    if (list[4].equals("未认证")) {
                        startActivityForResult(new Intent(CertificationCenterActivity.this, BankCardActivity.class), 6);

                    } else {
                        Toast.makeText(CertificationCenterActivity.this, "请按顺序认证", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case 5:
                    Intent intent = new Intent(CertificationCenterActivity.this, WebActivity.class);
                    url = NetRequestBusinessDefine.K_HOST_NAME + "/user/taobao?orderno=" + "&token=" + NetRequestBusinessDefine.K_TOKEN;
                    intent.putExtra("url", url);
                    startActivity(intent);
//                        startActivity(new Intent(CertificationCenterActivity.this,ZhiFuBaoActivity.class));
                    break;
                case 6:
                    Intent intent1 = new Intent(CertificationCenterActivity.this, WebActivity.class);
                    url = NetRequestBusinessDefine.K_HOST_NAME + "/user/fund?orderno=" + "&token=" + NetRequestBusinessDefine.K_TOKEN;
                    intent1.putExtra("url", url);
                    startActivity(intent1);
//                        startActivity(new Intent(CertificationCenterActivity.this,BankCardActivity.class));
                    break;
                case 7:
                    Intent intent2 = new Intent(CertificationCenterActivity.this, WebActivity.class);
                    url = NetRequestBusinessDefine.K_HOST_NAME + "/user/social?orderno=" + "&token=" + NetRequestBusinessDefine.K_TOKEN;
                    intent2.putExtra("url", url);
                    startActivity(intent2);
//                        startActivity(new Intent(CertificationCenterActivity.this,BankCardActivity.class));
                    break;
                default:
                    break;
            }
        });
    }

    private void initview() {
        btnGetAmount = (TextView) findViewById(R.id.btn_getamount);
        lvCertification = (ReListView) findViewById(R.id.lv_certification);
        tv_exit = (ImageView) findViewById(R.id.tv_exit);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_getamount:
                if (btnGetAmount.isSelected() != false) {
                    Toast.makeText(getApplicationContext(), "请完善信息后重试！", Toast.LENGTH_LONG).show();
                    return;
                }
                HomePresenterImpl homePresenter = new HomePresenterImpl(mHandler);
                homePresenter.getData();
                break;
            case R.id.tv_exit:
                tiShi.show();
                break;
        }
    }

    /**
     * 扫描身份证正反面请求码
     */
    private static final int LF_SCAN_ID_CARD_BOTH_REQUEST = 102;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == LF_SCAN_ID_CARD_BOTH_REQUEST) {//返回身份证正反面信息
            dealScanIDCardBothResult();
            return;
        } else if (requestCode == KEY_TO_DETECT_REQUEST_CODE) {//返回人相信息
            dealDetectResult(data, resultCode);
            return;
        }
        // RESULT_OK，判断另外一个activity已经结束数据输入功能，Standard activity result:
        switch (resultCode) {
            case 1:
                Log.e("xxxxxx", requestCode + "");
                list[0] = "已认证";
                certificationAdapter.notifyDataSetChanged();
                break;
            case 2:
                Log.e("xxxxxx", requestCode + "");
                list[1] = "已认证";
                certificationAdapter.notifyDataSetChanged();
                break;
            case 3:
                Log.e("xxxxxx", requestCode + "");
                list[2] = "已认证";
                certificationAdapter.notifyDataSetChanged();
                break;
            case 4:
                Log.e("xxxxxx", requestCode + "");
                list[3] = "已认证";
                certificationAdapter.notifyDataSetChanged();
                break;
            case 5:
                CenterPresenterImpl centerPresenter = new CenterPresenterImpl(mHandler);
                centerPresenter.postData();
                break;
            case 6:
                Log.e("xxxxxx", requestCode + "");
                list[5] = "已认证";
                certificationAdapter.notifyDataSetChanged();
                break;
            default:
                break;
        }
    }

    /**
     * 跳转扫描身份证界面，扫描正面和反面
     */
    private void toScanIdCardBoth() {
        Intent scanBothIdCardIntent = getScanBothIdCardIntent(LFIDCard.FRONT, "请将身份证正面放入扫描框内");
        startActivityForResult(scanBothIdCardIntent, LF_SCAN_ID_CARD_BOTH_REQUEST);
    }

    @Override
    public void onResume() {
        super.onResume();
        CenterPresenterImpl centerPresenter = new CenterPresenterImpl(mHandler);
        centerPresenter.postData();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        Intent intent = new Intent(CertificationCenterActivity.this, MainActivity.class);
        NetRequestBusinessDefine.login = true;
        startActivity(intent);
        CertificationCenterActivity.this.finish();
    }

    String zhenmian1, fanmian, renxiang, name, idcardNumber, StPD;

    public String savaFile(byte[] bytes, String name) {
        String path = "";
        try {
            File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + name + ".jpg");
            FileOutputStream fos = null;
            fos = new FileOutputStream(file);
            fos.write(bytes, 0, bytes.length);
            path = file.getPath();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return path;
    }

    /**
     * 对字节数组字符串进行Base64解码
     *
     * @param imgStr base64字符串
     * @return byte[]
     */
    public static byte[] changeBase64(String imgStr) {
        String base = "";
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] bytes = null;
        try {
            // Base64解码
            bytes = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {// 调整异常数据
                    bytes[i] += 256;
                }
            }
            // 生成jpeg图片
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bytes;
    }

    private static final int KEY_TO_DETECT_REQUEST_CODE = 2;

    /**
     * 跳转IDCard正反面扫描界面
     *
     * @param mode IDCard扫描类型
     */
    private Intent getScanBothIdCardIntent(int mode, String scanText) {
        Intent scanIntent = new Intent(this, IDCardBothActivity.class);
        scanIntent.putExtra(IDCardBothActivity.EXTRA_BACK_DRAWABLE_ID, R.mipmap.icon_scan_back);
        //设置身份证扫描类型
        scanIntent.putExtra(IDCardBothActivity.EXTRA_RECOGNIZE_MODE, mode);
        //设置身份证扫描文字
        scanIntent.putExtra(IDCardBothActivity.EXTRA_SCAN_TIPS, scanText);
        // 设置扫描界面方向为竖直，设备头部朝上
        scanIntent.putExtra(IDCardBothActivity.EXTRA_SCAN_ORIENTATION, getScanOrientation());
        // 设置需要返回身份证正面取景框的身份证图像
        scanIntent.putExtra(IDCardBothActivity.KEY_FRONT_CAMERA_APERTURE_BITMAP, true);
        // 设置需要返回身份证反面取景框的身份证图像
        scanIntent.putExtra(IDCardBothActivity.KEY_BACK_CAMERA_APERTURE_BITMAP, true);
        //设置是否开启扫描光标
        scanIntent.putExtra(IDCardBothActivity.EXTRA_SCAN_LINE_STATUS, LFSpUtils.getIsShowScanCursor(this));
        //扫描取景框边界颜色
        scanIntent.putExtra(IDCardBothActivity.EXTRA_SCAN_GUIDE_COLOR, Color.parseColor("#78FFFFFF"));
//        //是否需要在框内才能扫描，默认true
//        scanIntent.putExtra(IDCardBothActivity.EXTRA_SCAN_IS_IN_FRAME, getScanIsInFrame());
        //设置扫描的超时时间
        scanIntent.putExtra(IDCardBothActivity.EXTRA_SCAN_TIME_OUT, getScanTimeOut());
        //设置是否开启自动对焦，默认不开启
        scanIntent.putExtra(IDCardBothActivity.EXTRA_SCAN_AUTO_FOCUS, getScanIsAutoFocus());

        return scanIntent;
    }

    private int getScanOrientation() {
        int cardScanOrientation = CardActivity.ORIENTATION_PORTRAIT;
        int settingScanOrientation = LFSpUtils.getScanOrientation(this, 0);
        switch (settingScanOrientation) {
            case LFSettingUtils.LF_SCAN_ORIENTATION_PORTRAIT:
                cardScanOrientation = CardActivity.ORIENTATION_PORTRAIT;
                break;
            case LFSettingUtils.LF_SCAN_ORIENTATION_LANDSCAPE_LEFT:
                cardScanOrientation = CardActivity.ORIENTATION_LANDSCAPE_LEFT;
                break;
            case LFSettingUtils.LF_SCAN_ORIENTATION_LANDSCAPE_RIGHT:
                cardScanOrientation = CardActivity.ORIENTATION_LANDSCAPE_RIGHT;
                break;
            default:
                cardScanOrientation = CardActivity.ORIENTATION_PORTRAIT;
                break;
        }
        return cardScanOrientation;
    }

    /**
     * 获取扫描超时时间
     *
     * @return
     */
    private int getScanTimeOut() {
        return LFSpUtils.getScanTimeOut(this, 30);
    }

    /**
     * 获取是否开启自动对焦，默认为false
     *
     * @return
     */
    private boolean getScanIsAutoFocus() {
        return LFSpUtils.getScanAutoFocus(this);
    }

    /**
     * 处理扫描身份证正反面结果
     */
    private void dealScanIDCardBothResult() {
        LFIDCard idCardFrontResult = (LFIDCard) getReturnResult(IDCardBothActivity.KEY_FRONT_CARD_DATA);
        byte[] cameraApertureFrontImage = (byte[]) getReturnResult(IDCardBothActivity.KEY_FRONT_CAMERA_APERTURE_BITMAP);
        byte[] cameraApertureBackImage = (byte[]) getReturnResult(IDCardBothActivity.KEY_BACK_CAMERA_APERTURE_BITMAP);
        if (cameraApertureFrontImage != null && cameraApertureBackImage != null) {
            zhenmian1 = savaFile(cameraApertureFrontImage, "zhenmian");//身份证反面
            fanmian = savaFile(cameraApertureBackImage, "fanmian");//身份证正面
            name = idCardFrontResult.getName();
            idcardNumber = idCardFrontResult.getNumber();
            startLiveness();
        }
    }

    private Object getReturnResult(String key) {
        Object data = LFIntentTransportData.getInstance().getData(key);
        LFIntentTransportData.getInstance().removeData(key);
        return data;
    }

    private void startLiveness() {
        try {
            Bundle bundle = new Bundle();
            /**
             * OUTPUT_TYPE 配置, 传入的outputType类型为singleImg （单图），multiImg （多图），video（低质量视频），fullvideo（高质量视频）
             */
            bundle.putString(LivenessActivity.OUTTYPE, getOutputType());
            /**
             * EXTRA_MOTION_SEQUENCE 动作检测序列配置，支持四种检测动作， BLINK(眨眼), MOUTH（张嘴）, NOD（点头）, YAW（摇头）, 各个动作以空格隔开。 推荐第一个动作为BLINK。
             * 默认配置为"BLINK MOUTH NOD YAW"
             */
            bundle.putString(LivenessActivity.EXTRA_MOTION_SEQUENCE, getActionSequence());
            /**
             * SOUND_NOTICE 配置, 传入的soundNotice为boolean值，true为打开, false为关闭。
             */
            bundle.putBoolean(LivenessActivity.SOUND_NOTICE, LFSpUtils1.getMusicTipSwitch(this));
            /**
             * COMPLEXITY 配置, 传入的complexity类型为normal,支持四种难度，easy, normal, hard, hell.
             */
            bundle.putString(LivenessActivity.COMPLEXITY, getComplexity());

            Intent intent = new Intent();
            intent.setClass(this, LivenessActivity.class);
            intent.putExtras(bundle);
            //设置返回图片结果
            intent.putExtra(LivenessActivity.KEY_DETECT_IMAGE_RESULT, true);
            //设置返回protobuf结果
            intent.putExtra(LivenessActivity.KEY_DETECT_PROTO_BUF_RESULT, true);
            //设置返回video结果，video模式才会返回
            intent.putExtra(LivenessActivity.KEY_DETECT_VIDEO_RESULT, true);
            startActivityForResult(intent, KEY_TO_DETECT_REQUEST_CODE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取设置中设置好的outputType,
     * 若没有设置，默认传入Constants.SINGLEIMG，Constants.MULTIIMG，Constants.VIDEO三个中任意一个
     *
     * @return
     */
    private String getOutputType() {
        String outputType = Constants.MULTIIMG;
        outputType = LFSpUtils1.getOutputType(this, Constants.MULTIIMG);
        return outputType;
    }

    /**
     * 获取检测序列
     *
     * @return
     */
    private String getActionSequence() {
        String actionSequence = "";
        //是否使用随机序列
        boolean isRandomSequence = LFSpUtils1.getUseRandomSequence(this);
        if (isRandomSequence) {
            actionSequence = getRandomSequence();
        } else {
            actionSequence = LFSpUtils1.getActionSequence(this);
            //如果没有设置动作序列，则使用默认动作序列
            if (TextUtils.isEmpty(actionSequence)) {
                actionSequence = LFCommonUtils.getActionSequence(getDefaultSequenceList());
            }
        }
        return actionSequence;
    }

    private String getRandomSequence() {
        Random random = new Random();
        List<String> actionList = new ArrayList<>();
        for (int i = 0; ; i++) {
            int randomAction = random.nextInt(4);
            String actionByPosition = getActionByPosition(randomAction);
            if (!actionList.contains(actionByPosition)) {
                actionList.add(actionByPosition);
                if (actionList.size() >= 4) {
                    break;
                }
            }
        }
        return LFCommonUtils.getActionSequence(actionList);
    }

    private String getActionByPosition(int position) {
        String action = "";
        switch (position) {
            case 0:
                action = Constants.BLINK;
                break;
            case 1:
                action = Constants.MOUTH;
                break;
            case 2:
                action = Constants.NOD;
                break;
            case 3:
                action = Constants.YAW;
                break;
        }
        return action;
    }

    private List<String> getDefaultSequenceList() {
        List<String> sequenceDataList = new ArrayList<>();
        sequenceDataList.add(Constants.BLINK);
        sequenceDataList.add(Constants.MOUTH);
        sequenceDataList.add(Constants.NOD);
        sequenceDataList.add(Constants.YAW);

        return sequenceDataList;
    }

    /**
     * 获取难易程度，在Constants.EASY，Constants.NORMAL，Constants.HARD，Constants.HELL中选取一个,
     * 默认Constants.NORMAL
     *
     * @return
     */
    private String getComplexity() {
        String complexity = "";
        complexity = LFSpUtils1.getComplexity(this, Constants.NORMAL);
        return complexity;
    }

    private void initSDK() {
        //初始化Liveness SDK的License路径
        final String licPath = Constants1.LICENSE_MIDDLE_PATH + File.separator + Constants1.LICENSE_NAME;
        LFLivenessSDK.getInstance(this).initLicPath(licPath, Constants1.LICENSE_NAME);
        try {
            //获取剩余天数
            int remainingDays = LFLivenessSDK.getInstance(this).getRemainingDays();
            //License不在有效期内或到了更新的时间,则启动下载
            if (!LFLivenessSDK.getInstance(this).checkLicenseValid() || remainingDays < Constants1.DAYS_BEFORE_LIC_EXPIRED) {
                LFLiDownloadManager.getInstance(this).downLoadLic(Constants1.LICENSE_INFO_URL, (isSuccess, errorMsg) -> {
                    //下载完成的回调
                });
            }
        } catch (IllegalArgumentException e) {
        } catch (Exception e) {
            Toast.makeText(CertificationCenterActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
    }

    private void dealDetectResult(Intent data, int resultCode) {
        switch (resultCode) {
            case RESULT_OK:
                detectSuccess(data);
                break;
            case LivenessActivity.RESULT_SDK_INIT_FAIL_APPLICATION_ID_ERROR:
                Toast.makeText(this, "包名绑定错误！", Toast.LENGTH_LONG).show();
                break;
            case LivenessActivity.RESULT_SDK_INIT_FAIL_LICENSE_OUT_OF_DATE:
                Toast.makeText(this, "License过期,SDK权限过期！", Toast.LENGTH_LONG).show();
                break;
            case LivenessActivity.RESULT_SDK_INIT_FAIL_OUT_OF_DATE:
                Toast.makeText(this, "模型路径错误！", Toast.LENGTH_LONG).show();
                break;
            case LivenessActivity.RESULT_INTERNAL_ERROR:
                Toast.makeText(this, "其他错误 文案待定！", Toast.LENGTH_LONG).show();
                break;
            case LivenessActivity.RESULT_FAILED_NO_LIC_PATH:
                Toast.makeText(this, "获取License内容失败, 请确认License路径及名称！", Toast.LENGTH_LONG).show();
                break;
            case RESULT_CANCELED:
                Toast.makeText(this, "检测取消！", Toast.LENGTH_LONG).show();
                break;
        }
    }

    /**
     * 返回
     *
     * @param data
     */
    private void detectSuccess(Intent data) {
        mReturnResult = (LFReturnResult) data.getSerializableExtra(LivenessActivity.KEY_DETECT_RESULT);
        refreshData();
    }

    private String LF_APP_ID = "cbd024c4573e49679404a25ed78db390";
    private String LF_APP_SECRET = "66d9f084b5a94cd1822b07cd959056d1";
    String result = "";

    /**
     * 人脸比对接口
     */
    public void postselectProducts() {
        new Thread(() -> {
            try {
                result = upload().string();
                Gson gson = new Gson();
                postselectProductsBean bean = gson.fromJson(result, postselectProductsBean.class);
                if (bean.getStatus().equals("OK")) {
                    Intent intent = new Intent(CertificationCenterActivity.this, UserInfoActivity.class);
                    intent.putExtra("url_frontcard", zhenmian1);
                    intent.putExtra("url_backcard", fanmian);
                    intent.putExtra("url_photoliving", renxiang);
                    intent.putExtra("id_name", name);
                    intent.putExtra("id_no", idcardNumber);
                    intent.putExtra("result", result);
                    startActivityForResult(intent, 1);
                } else {
                    Toast.makeText(CertificationCenterActivity.this, "请重新扫描！", Toast.LENGTH_LONG).show();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();

    }

    private LFReturnResult mReturnResult;

    private void refreshData() {
        if (mReturnResult != null) {
            LFLivenessSDK.LFLivenessImageResult[] imageResultArr = mReturnResult.getImageResults();
            if (imageResultArr != null) {
                int size = imageResultArr.length;
                if (size > 0) {
                    LFLivenessSDK.LFLivenessImageResult imageResult = imageResultArr[0];
                    renxiang = savaFile(imageResult.image, "renxiang");//人像
                }
            }
            // protoBuf文件
            byte[] protoBuf = LFProtoBufUtil.getProtoBuf();
            StPD = savaFile1(protoBuf, "lala");
            postselectProducts();
        }
    }

    public String savaFile1(byte[] bytes, String name) {
        String path = "";
        try {
            File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + name + ".pb");
            FileOutputStream fos = null;
            fos = new FileOutputStream(file);
            fos.write(bytes, 0, bytes.length);
            path = file.getPath();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return path;
    }

    public ResponseBody upload() {
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("api_id", LF_APP_ID)
                .addFormDataPart("api_secret", LF_APP_SECRET)
                .addFormDataPart("name", name + "")
                .addFormDataPart("id_number", idcardNumber + "")
                .addFormDataPart("liveness_data_file", new File(StPD).getName(),
                        RequestBody.create(MediaType.parse("multipart/form-data"), new File(StPD)))
                .build();
        Request request = new Request.Builder()
                .url("https://cloudapi.linkface.cn/identity/liveness_idnumber_verification")
                .post(requestBody)
                .build();
        Response response = null;
        try {
            response = client.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (!response.isSuccessful()) try {
            throw new IOException("Unexpected code " + response);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response.body();
    }
}
